package com.splant.android.smart.UILevel.Community;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.content.PermissionChecker;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.splant.android.R;
import com.splant.android.smart.CommunicationLevel.sPlantAsyncHttpClient;
import com.splant.android.smart.CommunicationLevel.sPlantJsonHttpResponseHandler;
import com.splant.android.smart.Global;
import com.splant.android.smart.ModelLevel.AreaListBean;
import com.splant.android.smart.ModelLevel.WaterListBean;
import com.splant.android.smart.ModelLevel.WaterRecordListBean;
import com.splant.android.smart.ModelLevel.sPlantRequestParams;
import com.splant.android.smart.SystemDefinedLevel.GenericControls.Dialog.LoadingDialog;
import com.splant.android.smart.SystemDefinedLevel.Utils.System_Dimen_Util;
import com.splant.android.smart.UILevel.Community.fragments.Garden_AreaList_Adapter;
import com.splant.android.smart.UILevel.Community.fragments.Garden_DetectorList_Adapter;
import com.splant.android.smart.UILevel.Utils.sPlantUitl;

import org.apache.http.Header;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/12.
 */

public class Garden_WaterRecord_Activity extends Activity implements View.OnClickListener {


    private Button btn_goBack;
    private TextView tv_areaName;
    private RecyclerView rlv_waterList;

    private LinearLayout ll_switch1;
    private LinearLayout ll_switch2;
    private LinearLayout ll_switch3;

    private TextView tv_switch1Record;
    private TextView tv_switch2Record;
    private TextView tv_switch3Record;

    private TextView tv_switch1More;
    private TextView tv_switch2More;
    private TextView tv_switch3More;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.garden_waterrecord_activity);

        btn_goBack = (Button) findViewById(R.id.btn_goBack);
        tv_areaName = (TextView) findViewById(R.id.tv_areaName);
        rlv_waterList = (RecyclerView) findViewById(R.id.rlv_waterList);
        ll_switch1 = (LinearLayout) findViewById(R.id.ll_switch1);
        ll_switch2 = (LinearLayout) findViewById(R.id.ll_switch2);
        ll_switch3 = (LinearLayout) findViewById(R.id.ll_switch3);

        tv_switch1Record = (TextView) findViewById(R.id.tv_switch1Record);
        tv_switch2Record = (TextView) findViewById(R.id.tv_switch2Record);
        tv_switch3Record = (TextView) findViewById(R.id.tv_switch3Record);

        tv_switch1More = (TextView) findViewById(R.id.tv_switch1More);
        tv_switch2More = (TextView) findViewById(R.id.tv_switch2More);
        tv_switch3More = (TextView) findViewById(R.id.tv_switch3More);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        rlv_waterList.setLayoutManager(linearLayoutManager);

        init();

        btn_goBack.setOnClickListener(this);
        tv_areaName.setOnClickListener(this);
        tv_switch1More.setOnClickListener(this);
        tv_switch2More.setOnClickListener(this);
        tv_switch3More.setOnClickListener(this);
    }

    private sPlantAsyncHttpClient sPlantClient;

    private void init() {

        sPlantClient = sPlantAsyncHttpClient.getInstance();
        loadingDialog = LoadingDialog.createDialog(this);

        getWaterList();
    }

    private List<WaterListBean.Water> waterList = new ArrayList<>();
    private Garden_Water_Adapter garden_water_adapter;

    private void getWaterList() {

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());
        params.put("pageNo", -1);
        params.put("pageSize", 1000);

        if (areaId.equals("") == false)
            params.put("areaId", areaId);

        if (loadingDialog.isShowing() == false)
            loadingDialog.show();

        sPlantClient.get(sPlantAsyncHttpClient.GETWATERDEVICES, params, new sPlantJsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    if (response.getInt("succeed") == 1) {

                        loadingDialog.dismiss();
                        waterList.clear();

                        Gson gson = new Gson();
                        WaterListBean waterListBean = gson.fromJson(response.toString(), WaterListBean.class);
                        waterList.addAll(waterListBean.getWaterList());

                        if (waterListBean.getWaterList() != null && waterListBean.getWaterList().size() > 0) {

                            ll_switch1.setVisibility(View.VISIBLE);
                            ll_switch2.setVisibility(View.VISIBLE);
                            ll_switch3.setVisibility(View.VISIBLE);
                            selectedWater = waterList.get(0);

                        } else {

                            selectedWater = null;
                            ll_switch1.setVisibility(View.GONE);
                            ll_switch2.setVisibility(View.GONE);
                            ll_switch3.setVisibility(View.GONE);

                            Toast.makeText(Garden_WaterRecord_Activity.this, "该区域无设备", Toast.LENGTH_LONG).show();
                        }

                        garden_water_adapter = new Garden_Water_Adapter(Garden_WaterRecord_Activity.this, waterList);
                        rlv_waterList.setAdapter(garden_water_adapter);

                        if (selectedWater != null)
                            selectedWaters(selectedWater);

                        garden_water_adapter.setOnItemClickListener(new Garden_DetectorList_Adapter.onItemClickListener() {
                            @Override
                            public void onItemChick(int pos) {

                                selectedWater = waterList.get(pos);

                                garden_water_adapter.notifyDataSetChanged();

                                selectedWaters(waterList.get(pos));
                            }
                        });

                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                loadingDialog.dismiss();
                Toast.makeText(Garden_WaterRecord_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });

    }

    private List<AreaListBean.Area> areaList = new ArrayList<>();
    private String areaId = "";
    private boolean isGetAreaId = false;
    private WaterListBean.Water selectedWater;

    private void showAreaList() {
        if (isGetAreaId)
            return;
        isGetAreaId = true;

        View popupView = getLayoutInflater().inflate(R.layout.garden_arealist_popupwindow, null);

        final ListView lv_areaList = (ListView) popupView.findViewById(R.id.lv_areaList);

        final PopupWindow window = new PopupWindow(popupView, System_Dimen_Util.dip2px(this, 200), System_Dimen_Util.dip2px(this, 400));

        window.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#F8F8F8")));

        window.setFocusable(true);

        window.setOutsideTouchable(true);

        window.showAsDropDown(tv_areaName, 0, 2);

        RequestParams params = new RequestParams();
        params.put("userId", Global.user.getUserId());

        lv_areaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                window.dismiss();

                areaId = areaList.get(position).getAreaId();

                tv_areaName.setText(areaList.get(position).getAreaName());

                getWaterList();

            }
        });

        sPlantClient.get(sPlantAsyncHttpClient.GETAREALIST, params, new sPlantJsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                        try {
                            isGetAreaId = false;
                            if (response.getInt("succeed") == 1) {

                                Gson gson = new Gson();
                                AreaListBean areaListBean = gson.fromJson(response.toString(), AreaListBean.class);

                                if (areaListBean.getAreaList() != null && areaListBean.getAreaList().size() > 0) {

                                    areaList.clear();
                                    AreaListBean.Area areaAll = new AreaListBean.Area();
                                    areaAll.setAreaId("");
                                    areaAll.setAreaName("全部区域");

                                    areaList.add(areaAll);
                                    areaList.addAll(areaListBean.getAreaList());

                                    Garden_AreaList_Adapter garden_areaList_adapter = new Garden_AreaList_Adapter(Garden_WaterRecord_Activity.this, areaList);

                                    lv_areaList.setAdapter(garden_areaList_adapter);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                        isGetAreaId = false;
                        Toast.makeText(Garden_WaterRecord_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }

    private LoadingDialog loadingDialog;

    private void selectedWaters(WaterListBean.Water water) {

        int deviceType = sPlantUitl.getWaterType(water.getWaterId());

        if (deviceType == 1) {
            ll_switch2.setVisibility(View.INVISIBLE);
            ll_switch3.setVisibility(View.INVISIBLE);
        } else if (deviceType == 2) {
            ll_switch2.setVisibility(View.VISIBLE);
            ll_switch3.setVisibility(View.INVISIBLE);
        } else {
            ll_switch2.setVisibility(View.VISIBLE);
            ll_switch3.setVisibility(View.VISIBLE);
        }


        RequestParams params = new RequestParams();
        params.put("waterId", water.getWaterId());
        params.put("startTime", "");
        params.put("endTime", "");

        if (loadingDialog.isShowing() == false)
            loadingDialog.show();

        sPlantClient.get(sPlantAsyncHttpClient.GETWATERDATAS, params, new sPlantJsonHttpResponseHandler() {
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                try {
                    loadingDialog.dismiss();
                    if (response.getInt("succeed") == 1) {

                        Gson gson = new Gson();

                        WaterRecordListBean waterRecordListBean = gson.fromJson(response.toString(), WaterRecordListBean.class);

                        showWaterDatas(waterRecordListBean.getWaterDataList());

                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                loadingDialog.dismiss();
                Toast.makeText(Garden_WaterRecord_Activity.this, getString(R.string.system_request_error), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showWaterDatas(List<WaterRecordListBean.WaterData> waterDatas) {
        if (waterDatas != null) {
            String s1Datas = "";
            String s2Datas = "";
            String s3Datas = "";

            for (WaterRecordListBean.WaterData wd : waterDatas) {
                String data = wd.getWaterTime() + "  " + wd.getWaterLength() + "分钟 " + wd.getUserName() + "\n";
                if (wd.getSwitchNo() == 1)
                    s1Datas += data;
                else if (wd.getSwitchNo() == 2)
                    s2Datas += data;
                else
                    s3Datas += data;
            }


            tv_switch1Record.setText(s1Datas);

            if (tv_switch2Record != null)
                tv_switch2Record.setText(s2Datas);

            if (tv_switch3Record != null)
                tv_switch3Record.setText(s3Datas);

        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_goBack:
                finish();
                break;
            case R.id.tv_areaName:
                showAreaList();
                break;
            case R.id.tv_switch1More:

                Intent intent = new Intent(Garden_WaterRecord_Activity.this, Garden_WaterSwitchRecord_Activity.class);
                intent.putExtra("switchNo", 1);
                intent.putExtra("waterId", selectedWater.getWaterId());
                startActivity(intent);

                break;
            case R.id.tv_switch2More:

                Intent intent2 = new Intent(Garden_WaterRecord_Activity.this, Garden_WaterSwitchRecord_Activity.class);
                intent2.putExtra("switchNo", 2);
                intent2.putExtra("waterId", selectedWater.getWaterId());
                startActivity(intent2);

                break;
            case R.id.tv_switch3More:

                Intent intent3 = new Intent(Garden_WaterRecord_Activity.this, Garden_WaterSwitchRecord_Activity.class);
                intent3.putExtra("switchNo", 3);
                intent3.putExtra("waterId", selectedWater.getWaterId());
                startActivity(intent3);

                break;
        }
    }
}
